﻿using System;
using System.Text;

namespace SharpOSCAR.Base
{
    /// <summary>
    /// String data type
    /// </summary>
    public class String08 : ProtocolData, IString
    {
        private string _Value;
        /// <summary>
        /// Gets/sets the underlying string value
        /// </summary>
        public string Value
        {
            get { return _Value; }
            set { _Value = value; }
        }
        
        /// <summary>
        /// Returns a byte array representing the string
        /// </summary>
        /// <returns>Returns a byte array representing the string</returns>
        public override byte[] ToByteArray()
        {
            // Convert the string into a UTF8 byte array
            byte[] strBytes = Encoding.UTF8.GetBytes(_Value);
            // Create a buffer
            byte[] value = new byte[strBytes.Length + 1];
            // Write the length of the string byte array
            value[0] = Convert.ToByte(strBytes.Length);
            // Write the string byte array into the buffer
            Buffer.BlockCopy(strBytes, 0, value, 1, strBytes.Length);

            return value;
        }

        /// <summary>
        /// Returns a byte array representing the string in "compressed" format
        /// </summary>
        /// <returns>Returns a byte array representing the string in "compressed" format</returns>
        public byte[] ToByteArrayCompressed()
        {
            // Convert the string to lowercase and remove all spaces
            string compressed = _Value.ToLower().Replace(" ", "");
            // Convert the compressed string into a UTF8 byte array
            byte[] strBytes = Encoding.UTF8.GetBytes(compressed);
            // Create a buffer
            byte[] value = new byte[strBytes.Length + 1];
            // Write the length of the string to the array
            value[0] = Convert.ToByte(strBytes.Length);
            // Write the string byte array into the buffer
            Buffer.BlockCopy(strBytes, 0, value, 1, strBytes.Length);

            return value;
        }
    }
}
